const { createValidationError } = require('../utils/errors');

function validateBody(schema) {
  return (req, _res, next) => {
    const parsed = schema.safeParse(req.body);
    if (!parsed.success) {
      return next(createValidationError(parsed.error.flatten()));
    }
    req.body = parsed.data;
    next();
  };
}

function validateQuery(schema) {
  return (req, _res, next) => {
    const parsed = schema.safeParse(req.query);
    if (!parsed.success) {
      return next(createValidationError(parsed.error.flatten()));
    }
    req.query = parsed.data;
    next();
  };
}

module.exports = {
  validateBody,
  validateQuery
};
